from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import TimeoutException
from pyquery import PyQuery as pq
import requests

import re

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 20)
import time





def search():
    try:
        browser.get('https://uland.taobao.com/sem/tbsearch?refpid=mm_26632258_3504122_32538762&keyword=&clk1=0bd0533f5b82e573371ec7b88a96cea9&upsid=0bd0533f5b82e573371ec7b88a96cea9')
        input = wait.until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))
        )
        input.clear()
        input.send_keys('香水')
        input.send_keys(Keys.ENTER)
        total = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#J_waterfallPagination > div > div > span.totalPage')))
        return total[0].text
    except TimeoutException:
        search()


def next_page(page_number):
    try:
        browser.switch_to.window(browser.window_handles[1])
        browser.get('https://uland.taobao.com/sem/tbsearch?spm=a2e15.8261149.07626516003.3.265229b49zFMpB&refpid=mm_26632258_3504122_32538762&clk1=0bd0533f5b82e573371ec7b88a96cea9&keyword=%E9%A6%99%E6%B0%B4&' + 'page=%s' % page_number + '&_input_charset=utf-8')
        num = browser.find_element_by_css_selector('#Jumper')
        num.send_keys(page_number)
        # html = requests.get('https://uland.taobao.com/sem/tbsearch?spm=a2e15.8261149.07626516003.3.265229b49zFMpB&refpid=mm_26632258_3504122_32538762&clk1=0bd0533f5b82e573371ec7b88a96cea9&keyword=%E9%A6%99%E6%B0%B4&' + 'page=%s' % page_number + '&_input_charset=utf-8')
        # a = pq(browser.page_source)
        # a('#Jumper').attr('value', str(page_number))
        # submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#J_waterfallPagination > div > div > a.pageConfirm')))
        # input.clear()
        # browser.execute_script('$("#Jumper").val("%s")' % page_number)
        # print(browser)
        submit = browser.find_element_by_css_selector('#J_waterfallPagination > div > div > a.pageConfirm')
        submit.click()
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, '#J_waterfallPagination > div > div > span.page-cur'), str(page_number)))
        print('结束一页%s' % page_number)
    except TimeoutException:
        next_page(page_number)


def main():
    total = search()
    total2 = int(re.compile('(\d+)').search(total).group(1))
    for i in range(2, total2+1):
        next_page(i)



if __name__ == '__main__':
    main()